<?php


namespace App\Web\Model;


use EchoPHP\Facades\Db;
use EchoPHP\Facades\Log;

class OperatorLog {

    //个人账号管理模块
    const MODULE_ACCOUNT = 'account';
    //用户管理模块
    const MODULE_USERMANAGER = 'usermanager';
    //角色管理模块
    const MODULE_ROLEMANAGER = 'rolemanager';
    //团队管理模块
    const MODULE_TEAMMANAGER = 'teammanager';
    //下载数管理模块
    const MODULE_DOWNLOADCOUNT = 'downloadcount';
    //任务管理模块
    const MODULE_TASKMANAGER = 'taskmanager';

    /**
     * 记录操作日志
     * @param $oprId
     * @param $module
     * @param $message
     * @param array $context
     * @throws \Exception
     */
    public static function addLog($oprId, $module, $message, array $context = []) {
        $logType = config('app.oprlog.logtype', 'logfile');
        if ($logType == 'database') {
            $result = self::writeToDb($oprId, $module, $message, $context);
            if ($result) {
                return;
            }
            Log::error('数据库记录操作日志失败，继续使用文件存储');
        }
        self::writeToFile($oprId, $module, $message, $context);

    }

    /**
     * database记录数据库操作日志
     * @param $oprId
     * @param $module
     * @param $message
     * @param array $context
     * @return bool
     */
    private static function writeToDb($oprId, $module, $message, array $context = []) {
        $sql = 'INSERT INTO OperatorLog(oprid, module, message, context, createdate, updatedate) VALUES(?,?,?,?, Now(), Now())';
        $var = [$oprId, $module, $message, json_encode($context)];

        return Db::insert($sql, $var);
    }

    /**
     * 记录文件日志
     * @param $oprId
     * @param $module
     * @param $message
     * @param array $context
     */
    private static function writeToFile($oprId, $module, $message, array $context = []) {
        $context['oprid'] = $oprId;
        $context['module'] = $module;
        Log::info($message, $context, 'oprlog');
    }
}